package uccimpl;

import java.util.ArrayList;

import ucc.Service;
import util.CheckParameters;
import util.Utils;
import daoimpl.DebtDaoImpl;
import domain.Debt;
import domain.Person;
import exceptions.*;

public class DebtService extends Service<Debt> {
	
	private static DebtService instance;
	private DebtDaoImpl dao;
	private PersonService personService;
	
	protected DebtService(DebtDaoImpl dao) {
		super(dao);
		this.dao = dao;
		this.personService = PersonService.getInstance();
	}
	
	public static DebtService getInstance() {
		if (instance == null) {
			instance = new DebtService(new DebtDaoImpl());
		}
		return instance;
	}

	public ArrayList<Debt> findDebtBySource(Person source) throws NullParameterException {
		CheckParameters.checkNull(source, "source");
		return dao.findDebtBySource(source);
	}

	public ArrayList<Debt> findDebtByOwedTo(Person owedTo) throws NullParameterException {
		CheckParameters.checkNull(owedTo, "owedTo");
		return dao.findDebtByOwedTo(owedTo);
	}

	public ArrayList<Debt> getAllDebtsForMonth(String month) throws NullParameterException, InvalidParameterException {
		CheckParameters.checkStringEmpty(month, "month");
		return dao.getAllDebtsForMonth(month);
	}

	@Override
	protected void businessRules(Debt entity) throws NullParameterException,
			InvalidParameterException {
		CheckParameters.checkNull(entity, "entity");
		CheckParameters.checkNotZero(entity.getAmount(), "amount");
		CheckParameters.checkNull(entity.getSource(), "source");
		CheckParameters.checkNull(entity.getOwedTo(), "owed to");
		if (entity.getDate() == null || entity.getDate().equals("")) {
			entity.setDate(Utils.newDateToString());
		}
		if (entity.getDateDone() == null) {
			entity.setDateDone("");
		}
		if (entity.getSource().getId() == -1) {
			Person source = this.personService.add(entity.getSource());
			entity.setSource(source);
		}
		if (entity.getOwedTo().getId() == -1) {
			Person owedTo = this.personService.add(entity.getOwedTo());
			entity.setOwedTo(owedTo);
		}
	}

}
